﻿using J.IRepository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace J.FoodRepository
{
    public class BackRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly ISqlSugarClient _db;

        public BackRepository(ISqlSugarClient db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddAsync(T item)
        {
            return await _db.Insertable<T>(item).ExecuteCommandAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task<int> DeleteAsync(int id)
        {
            return await _db.Deleteable<T>(id).In(id).ExecuteCommandAsync();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAllAsync()
        {
            return await _db.Queryable<T>().ToListAsync();
        }
        /// <summary>
        /// 多条件查询
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expression)
        {
            return await _db.Queryable<T>().Where(expression).ToListAsync();
        }
        /// <summary>
        /// 单条件查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> GetModelAsync(int id)
        {
            return await _db.Queryable<T>().InSingleAsync(id);  
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdateAsync(T item)
        {
            return await _db.Updateable<T>(item).ExecuteCommandAsync();
        }
    }
}
